package com.sl.au.service.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sl.au.entity.Quote;
import com.sl.au.entity.QuoteDevice;
import com.sl.au.entity.QuoteForeign;
import com.sl.au.entity.QuoteReplacement;
import com.sl.au.repository.QuoteDeviceRepository;
import com.sl.au.repository.QuoteForeignRepository;
import com.sl.au.repository.QuoteReplacementRepository;
import com.sl.au.service.AuditNodeService;
import com.sl.au.service.DocService;
import com.sl.au.service.InventoryReduceService;
import com.sl.au.service.QuoteForeignService;
import com.sl.utils.DataConverter;

@Service("QuoteForeignService")
@Transactional
public class QuoteForeignServiceImpl extends BaseServiceImpl implements QuoteForeignService {

	@Autowired
	QuoteForeignRepository quoteForeignRepository;
	@Autowired
	QuoteDeviceRepository quoteDeviceRepository;
	@Autowired
	QuoteReplacementRepository quoteReplacementRepository;
	@Autowired
	InventoryReduceService inventoryReduceService;

	@Autowired
	AuditNodeService auditNodeService;

	@Override
	public QuoteForeignRepository getRepository() {
		return this.quoteForeignRepository;
	}

	@Override
	public QuoteDeviceRepository getDeviceRepository() {
		return this.quoteDeviceRepository;
	}

	@Override
	public QuoteReplacementRepository getReplacementRepository() {
		return this.quoteReplacementRepository;
	}

	// 得到外贸价格单列表
	@Override
	public List<QuoteForeign> getQuoteForeign(int start, int length, Map<String, String> condition, String orderName,
			String dir) {
		Page<QuoteForeign> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
		if (condition.get("dataFilter").equals("所有")){
			if(condition.get("auditState").equals("未审批")){
				pages = quoteForeignRepository.findAllQuoteForeignByKey(condition.get("key"), pageable);
			}else if(condition.get("auditState").equals("全部")){
				pages = quoteForeignRepository.findAllQuoteForeignByKeyAll(condition.get("key"), pageable);
			}else{
				pages = quoteForeignRepository.findAllQuoteForeignByKey(condition.get("key"),condition.get("auditState"), pageable);
			}
		}
		else if (condition.get("dataFilter").equals("本部门")){
			if(condition.get("auditState").equals("未审批")){
				pages = quoteForeignRepository.findSuperiorPage(condition.get("key"), condition.get("superior"), condition.get("userId"), pageable);
			}else if(condition.get("auditState").equals("全部")){
				pages = quoteForeignRepository.findSuperiorPageAll(condition.get("key"), condition.get("superior"), condition.get("userId"), pageable);
			}else{
				pages = quoteForeignRepository.findSuperiorPage(condition.get("key"), condition.get("superior"), condition.get("userId"),condition.get("auditState"), pageable);
			}
		}
		else if (condition.get("dataFilter").equals("本片区")){
			if(condition.get("auditState").equals("未审批")){
				pages = quoteForeignRepository.finAreaPage(condition.get("key"), condition.get("areaId"),  condition.get("userId"),pageable);
			}else if(condition.get("auditState").equals("全部")){
				pages = quoteForeignRepository.finAreaPageAll(condition.get("key"), condition.get("areaId"),  condition.get("userId"),pageable);
			}else{
				pages = quoteForeignRepository.finAreaPage(condition.get("key"), condition.get("areaId"),  condition.get("userId"),condition.get("auditState"),pageable);
			}
			//pages = quoteForeignRepository.finAreaPage(condition.get("key"), condition.get("areaId"),  condition.get("userId"),pageable);
		}
		else{
			if(condition.get("auditState").equals("未审批")){
				pages = quoteForeignRepository.findSelfPage(condition.get("key"), condition.get("userId"), pageable);
				//pages = quoteForeignRepository.finAreaPage(condition.get("key"), condition.get("areaId"),  condition.get("userId"),pageable);
			}else if(condition.get("auditState").equals("全部")){
				pages = quoteForeignRepository.findSelfPageAll(condition.get("key"), condition.get("userId"), pageable);
			}else{
				pages = quoteForeignRepository.findSelfPage(condition.get("key"), condition.get("userId"),condition.get("auditState"), pageable);
				//pages = quoteForeignRepository.finAreaPage(condition.get("key"), condition.get("areaId"),  condition.get("userId"),condition.get("auditState"),pageable);
			}
		}
			//pages = quoteForeignRepository.findSelfPage(condition.get("key"), condition.get("userId"), pageable);
		return pages.getContent();
	}
    //
	@Override
	public String genQuoteForeignDocx(String quoteForeignId) {
		String filename = null;
		DecimalFormat df = new DecimalFormat( "###############0.00 ");
		QuoteForeign quoteForeign = quoteForeignRepository.findOne(quoteForeignId);
		if (null != quoteForeign) {
			Map<String, Object> data = new HashMap<>();
			Map<String, LinkedList<List<String>>> tablesData = new HashMap<>();
			List<QuoteDevice> quoteForeignDevices = getDeviceRepository().findQuoteForeignDeviceList(quoteForeignId);
			List<QuoteReplacement> quoteForeignOtherDevices=getReplacementRepository().findQuoteForeignOtherDeviceList(quoteForeignId);
			LinkedList<List<String>> linkedQuoteDevices = new LinkedList<>();
			List<String> row;
			int order = 0;
			for (QuoteDevice device : quoteForeignDevices) {
				if(device.getLinkDeviceId()==null){
				row = new ArrayList<>();
				row.add((++order) + "");
				row.add(device.getProductName());
				row.add(device.getProductType());
				row.add(device.getUnit());
				row.add(device.getNumber() + "");
				row.add(df.format(device.getUnitPrice()) + "");
				double sum = device.getNumber() * device.getUnitPrice();
				row.add(df.format(sum) + "");
				row.add("");
				linkedQuoteDevices.add(row);
				}
			}
			for (QuoteReplacement OtherDevice : quoteForeignOtherDevices) {
				row = new ArrayList<>();
				row.add((++order) + "");
				row.add(OtherDevice.getDeviceName());
				row.add(OtherDevice.getType());
				row.add(OtherDevice.getUnit());
				row.add(OtherDevice.getAmount() + "");
				row.add(df.format(OtherDevice.getPrice()) + "");
				double sum = OtherDevice.getAmount() * Double.valueOf(OtherDevice.getPrice());
				row.add(df.format(sum) + "");
				row.add("");
				linkedQuoteDevices.add(row);
			}
			tablesData.put("d", linkedQuoteDevices);
			
			Map<String, String> textData = new HashMap<>();
			textData.put("customerName",quoteForeign.getCustomerName());
			textData.put("name",quoteForeign.getName());
//			textData.put("userName", quoteForeign.getUser().getEmpLogin().getName());
			textData.put("quoteDate", DataConverter.toDateYMD(quoteForeign.getCreateTime()));
			//System.out.println(df.format(quoteForeign.getSum()));
			textData.put("Sum",String.valueOf(df.format(quoteForeign.getSum())));
//			textData.put("guaranteeMonths", "24");
			data.put("textData", textData);
			data.put("tablesData", tablesData);
			filename = DocService.genTemplate("外贸价格单模板.docx", data, "外贸报价单");
		}
		return filename;
	}
	@Override
	public long getQuoteForeignCount(Map<String, String> condition) {
		long count = 0;
		if (condition.get("dataFilter").equals("所有")){
			if(condition.get("auditState").equals("未审批")){
				count = quoteForeignRepository.findAllCountwsp(condition.get("key"));
			}else if(condition.get("auditState").equals("全部")){
				count = quoteForeignRepository.findAllCount(condition.get("key"));
			}else{
				count = quoteForeignRepository.findAllCount(condition.get("key"),condition.get("auditState"));
			}
			//count = quoteForeignRepository.findAllCount(condition.get("key"));
		}else if (condition.get("dataFilter").equals("本部门")){
			if(condition.get("auditState").equals("未审批")){
				count = quoteForeignRepository.findSuperiorCountwsp(condition.get("key"), condition.get("userId"), condition.get("superior"));
			}else if(condition.get("auditState").equals("全部")){
				count = quoteForeignRepository.findSuperiorCount(condition.get("key"), condition.get("userId"), condition.get("superior"));
			}else{
				count = quoteForeignRepository.findSuperiorCount(condition.get("key"), condition.get("userId"), condition.get("superior"),condition.get("auditState"));
			}
		}
			
		else if (condition.get("dataFilter").equals("本片区")){
			if(condition.get("auditState").equals("未审批")){
				count = quoteForeignRepository.findAreaCountwsp(condition.get("key"), condition.get("userId"), condition.get("areaId"));
			}else if(condition.get("auditState").equals("全部")){
				count = quoteForeignRepository.findAreaCount(condition.get("key"), condition.get("userId"), condition.get("areaId"));
			}else{
				count = quoteForeignRepository.findAreaCountwsp(condition.get("key"), condition.get("userId"), condition.get("areaId"),condition.get("auditState"));
			}
		}
			//count = quoteForeignRepository.findAreaCount(condition.get("key"), condition.get("userId"), condition.get("areaId"));
		else
		{
			if(condition.get("auditState").equals("未审批")){
				count = quoteForeignRepository.findSelfCountwsp(condition.get("key"), condition.get("userId"));
			}else if(condition.get("auditState").equals("全部")){
				count = quoteForeignRepository.findSelfCount(condition.get("key"), condition.get("userId"));
			}else{
				count = quoteForeignRepository.findSelfCount(condition.get("key"), condition.get("userId"),condition.get("auditState"));
			}
		}
			//count = quoteForeignRepository.findSelfCount(condition.get("key"), condition.get("userId"));
		return count;
	}

	// 根据价格单Id得到价格单泵设备细目
	@Override
	public List<QuoteDevice> getQuoteDevice(int start, int length, String quoteForeignId, String orderName,
			String dir) {
		
		Page<QuoteDevice> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime","isInventory");
		pages = quoteDeviceRepository.findQuoteDevice(quoteForeignId, pageable);
		return pages.getContent();
	}

	// 得到其他细目
	@Override
	public List<QuoteReplacement> getQuoteReplacement(int start, int length, String quoteForeignId, String orderName,
			String dir) {
		Page<QuoteReplacement> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.ASC, "createTime");
		pages = quoteForeignRepository.findQuoteReplacement(quoteForeignId, pageable);
		return pages.getContent();
	}

	/**
	 * @param id
	 *            关联细目QuoteDevice的Id 得到降库状态
	 * @return
	 */
	// private String getStateByQuoteDeviceId(String id) {
	// String condition="0";
	// List<InventoryReduce> list=
	// inventoryReduceService.getRepository().findByQuoteDeviceId(id);
	// if(list.size()>0){
	// condition = "1";
	// }
	// else if(list.size()==0){
	// condition = "0";
	// }
	// return condition;
	// }

	// 得到当前进行降库设备
	@Override
	public List<QuoteDevice> getNowQuoteDevice(int start, int length, String nowDataId, String orderName, String dir) {
		Page<QuoteDevice> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
		pages = quoteDeviceRepository.getNowQuoteDevice(nowDataId, pageable);
		return pages.getContent();
	}

	@Override
	public void saveProcessStart(String quoteForeignId, ProcessInstance pInst) {
		QuoteForeign quoteForeign = quoteForeignRepository.getOne(quoteForeignId);
		if (null == pInst || null == quoteForeign)
			return;
		// 如果是重新提交审批，删除原来的审批节点
		auditNodeService.getRepository().deleteByPInstId(quoteForeign.getProcessInstId());
		quoteForeign.setProcessInstId(pInst.getId());
		quoteForeign.setAuditState("已提交");
		quoteForeign.setStartDate(new Date());

	}

	@Override
	public List<QuoteForeign> getForeignQuoteInState(int start, int length, String key, String audit, String superior) {
		Page<QuoteForeign> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
		pages = quoteForeignRepository.getAuditQuotes(key, audit, superior, pageable);
		return pages.getContent();
	}
	
	// 得到其他细目
			@Override
			public List<QuoteReplacement> getQuoteReplacementER(int start, int length, Map<String, String> condition, String orderName,
					String dir) {
				Page<QuoteReplacement> pages = null;
				Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
				pages = quoteForeignRepository.findQuoteReplacementER(condition.get("quoteId"), condition.get("key"), pageable);
				return pages.getContent();
			}

			@Override
			public List<QuoteReplacement> getQuoteReplacementERprice(int start, int length, Map<String, String> condition,
					String orderName, String dir) {
				Page<QuoteReplacement> pages = null;
				Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
				pages = quoteForeignRepository.findQuoteReplacementERprice(condition.get("type"), condition.get("deviceName"), condition.get("material"), pageable);
				return pages.getContent();
			}

}
